/// <reference types="vite/client" />

import { defineConfig, splitVendorChunkPlugin, loadEnv, PluginOption } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

import markdown from './build/markdown'
import vitePluginInspect from 'vite-plugin-inspect'
import pages from 'vite-plugin-pages'
import dts from 'vite-plugin-dts'


import path from 'path'
import vitePluginsMd from './build/vitePluginsMd'

export default ({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) }

  const plugins:PluginOption[] = [
    splitVendorChunkPlugin(),
    vue({
      include: [ /\.vue$/, /\.md$/, /\.preview/ ], // .preview: 将虚拟模块添加到 vue 解析
    }),
    vueJsx(),
    markdown(),
    vitePluginInspect(),
    vitePluginsMd(),
    // dts(), // 打包组件时生成 *.d.ts 声明文件
    pages({
      pagesDir: [
        { dir: 'src/components', baseRoute: '/components' },
        { dir: 'src/docs', baseRoute: '/docs' },
      ],
      extensions: [ 'md' ],
    }),
  ]

  if (process.env.VITE_USER_NODE_ENV === 'lib') {
    plugins.push(dts()) // 打包组件时生成 *.d.ts 声明文件
  }

  return defineConfig({
    build: {
      outDir: process.env.VITE_APP_DIR,
      ...process.env.VITE_USER_NODE_ENV === 'lib'
        ? {
          target: 'modules',
          lib: {
            name: 'cbm-vue-components',
            entry: './src/build.ts',
            formats: [ 'es', 'umd' ],
            fileName: (format) => `cbm-vue-components.${format}.js`, // 打包后的文件名
          },
        } : {},
      // sourcemap: true, // 输出.map文件
      rollupOptions: {
        external: process.env.VITE_USER_NODE_ENV === 'lib' ? [ 'vue' ] : [], // 排除依赖
        output: {
          chunkFileNames: (modules) => {
            if (modules.facadeModuleId?.endsWith('.vue')) {
              const arrId = modules.facadeModuleId.split(path.resolve('/'))

              return `${arrId[arrId.length - 2]}.js`
            }
            return '[name].js'
          },
          // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
          globals: {
            vue: 'Vue',
          },
        },
      },
    },
    plugins: plugins,
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '#': path.resolve(__dirname, './'),
        'type': path.resolve(__dirname, './src/type'),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "src/assets/styles/var.scss";',
        },
      },
    },
  })
}